//
//  STMHomeViewController.m
//  StoreManagement
//
//  Created by centling on 16/5/11.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMHomeViewController.h"
#import "STMHomeSectionView.h"
#import "STMHomeSectionCellView.h"
#import "STMHomeSectionImageCellView.h"
#import "STMOrderManagementMainController.h"
#import "STMTrueOrderViewController.h"
#import "STMOrderStatusViewController.h"
#import "STMShopManagementViewController.h"
#import "STMLoginViewController.h"
#import "STMTopTenFlowViewController.h"
#import "STMGoodsManagementViewController.h"
#import "STMConsultManagementViewController.h"
#import "STMStoreRefundViewController.h"
#import "STMSettingViewController.h"
#import "STMServiceIMViewController.h"
#import "STMGoodsPublishViewController.h"

@interface STMHomeViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *homeScrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIView *homeHeaderView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewHeight;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIImageView *storeIconImageView;
@property (weak, nonatomic) IBOutlet UILabel *storeNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *settingButton;

@property (nonatomic, strong) NSMutableArray *sectionCellNumArray;
@property (nonatomic, assign) BOOL refreshing;

@end

@implementation STMHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.refreshing = NO;
    self.storeIconImageView.layer.cornerRadius = 40;
    self.storeIconImageView.layer.masksToBounds = YES;
    UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(iconTap)];
    [self.storeIconImageView addGestureRecognizer:iconTap];
    self.storeIconImageView.userInteractionEnabled = YES;
    [self.settingButton addTarget:self action:@selector(pushSettingVC) forControlEvents:UIControlEventTouchUpInside];
    self.homeScrollView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    [self.homeScrollView.mj_header beginRefreshing];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData) name:nHomePageRefresh object:nil];
}



- (void)getData {
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getHomePageDataWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                      success:^(STMHomePageModel *result) {
                                          [SVProgressHUD dismiss];
                                          self.refreshing = NO;
                                          [self.homeScrollView.mj_header endRefreshing];
                                          if ([result.code isEqualToString:@"200"]) {
                                              self.sectionCellNumArray = [NSMutableArray arrayWithObjects:result.result.payment,result.result.delivery,result.result.no_receipt,result.result.consult,result.result.refund,result.result.returnNum, nil];
                                              
                                              for (int i = 1; i < self.contentView.subviews.count;) {
                                                  UIView *subview = self.contentView.subviews[i];
                                                  [subview removeFromSuperview];
                                              }
                                              self.storeNameLabel.text = result.result.store_name;
                                              [self.storeIconImageView sd_setImageWithURL:[NSURL URLWithString:result.result.store_logo] placeholderImage:nil];
                                              [self loadSectionViewData];
                                              
                                          } else if ([result.code isEqualToString:@"401"]) {
                                              STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
                                              [self presentViewController:loginVC animated:YES completion:nil];
                                              loginVC.backButton.hidden = YES;
//                                              __weak typeof(self) weakSelf = self;
//                                              loginVC.loginVCBlock = ^{
//                                                  [weakSelf getData];
//                                              };
                                          } else {
                                              [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                          }
                                      }
                                      failure:^(NSError *err) {
                                          self.refreshing = NO;
                                          [self.homeScrollView.mj_header endRefreshing];
                                          [SVProgressHUD dismiss];
                                          [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                      }];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([self.presentedViewController isKindOfClass:[STMLoginViewController class]]) {
        return;
    } else {
        self.navigationController.navigationBarHidden = NO;
    }
}


//- (void)login {
//    STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
//    [self.navigationController presentViewController:loginVC animated:YES completion:nil];
//}

- (void)pushSettingVC {
    STMSettingViewController *settingVC = [[STMSettingViewController alloc] init];
    [settingVC customNavigationTitle:@"设置"];
    [self.navigationController pushViewController:settingVC animated:YES];
}


- (void)buildSectionView {
    NSArray *titleArray = @[@"订单管理", @"售后服务", @"数据统计", @"商店管理"];
    CGFloat sectionViewHeight = 140;
    for (int i = 0; i < 4; i ++) {
        STMHomeSectionView *sectionView = [[[NSBundle mainBundle] loadNibNamed:@"STMHomeSectionView" owner:self options:nil] lastObject];
        sectionView.titleLabel.text = titleArray[i];
        sectionView.frame = CGRectMake(0, CGRectGetMaxY(self.homeHeaderView.frame)+ (i+1)*15 + i*sectionViewHeight, SCREEN_W, sectionViewHeight);
        __weak typeof(self) weakSelf = self;
        sectionView.block = ^(){
            [weakSelf pushNewControllerWithTag:0];
        };
        if (i > 0) {
            sectionView.moreButton.hidden = YES;
        }
        [self.contentView addSubview:sectionView];
    }
    self.contentViewHeight.constant = CGRectGetMaxY([self.contentView.subviews lastObject].frame) +10;
}

- (void)loadSectionViewData {
    [self buildSectionView];
    NSArray *nameArray = @[@[@"待付款",@"待发货",@"待收货"],@[@"咨询数",@"退款数",@"退货数"],@[@"商店流量",@"订单统计",@"Top10"],@[@"商品管理",@"店铺管理",@"客服IM"]];
    for (int i = 0; i < 4; i ++) {
        CGFloat originX = 10;
        CGFloat cellWidth = (SCREEN_W-40)/3;
        for (int j = 0; j < 3; j ++) {
            if (i < 2) {
                STMHomeSectionCellView *cellView = [STMHomeSectionCellView loadViewWithName:nameArray[i][j] numStr:self.sectionCellNumArray[i*3+j]];
                cellView.frame = CGRectMake(originX + j*(cellWidth + 10), 60, cellWidth, 60);
                cellView.tag = i*3 + j;
                __weak typeof(self) weakSelf = self;
                cellView.cellBlock = ^(NSInteger tag){
                    [weakSelf pushNewControllerWithTag:tag];
                };
                [self.contentView.subviews[i+1] addSubview:cellView];
            } else {
                STMHomeSectionImageCellView *imageCell = [STMHomeSectionImageCellView loadViewWithImage:[NSString stringWithFormat:@"image%d",(i-2)*3+j+1] name:nameArray[i][j]];
                imageCell.frame = CGRectMake(originX + j*(cellWidth + 10), 40, cellWidth, 90);
                imageCell.tag = i*3 + j;
                __weak typeof(self) weakSelf = self;
                imageCell.cellBlock = ^(NSInteger tag){
                    [weakSelf pushNewControllerWithTag:tag];
                };
                [self.contentView.subviews[i+1] addSubview:imageCell];
            }
        }
    }
}

- (void)pushNewControllerWithTag:(NSInteger)tag {
    if (tag < 3) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"待付款",@"待发货",@"待收货",@"已完成",@"已取消"];
        NSArray *typeArray = @[@"10",@"20",@"30",@"40",@"0"];
        NSArray *changeButtonTitleIndexArray = @[@"0",@"1",@"2",@"2",@"3"];
//        NSArray *colorArray = @[[UIColor redColor],[UIColor blueColor],[UIColor greenColor],[UIColor grayColor],[UIColor whiteColor]];
        
        for (int i = 0; i < 5; i ++) {
            STMOrderStatusViewController *childVC = [[STMOrderStatusViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.orderType = typeArray[i];
            childVC.changeButtonTitleIndex = changeButtonTitleIndexArray[i];
            [vcArray addObject:childVC];
        }
        STMTrueOrderViewController *orderManagementVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        [orderManagementVC customNavigationTitle:@"全部订单"];
        orderManagementVC.selectedTab = tag;
        orderManagementVC.forSaleService = YES;
        [self.navigationController pushViewController:orderManagementVC animated:YES];
    } else if (tag == 3) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"未回复",@"已回复"];
        NSArray *typeArray = @[@"to_reply",@"replied"];
//        NSArray *colorArray = @[[UIColor redColor],[UIColor blueColor]];
        
        for (int i = 0; i < 2; i ++) {
            STMConsultManagementViewController *childVC = [[STMConsultManagementViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.consultType = typeArray[i];
            [vcArray addObject:childVC];
        }
        STMTrueOrderViewController *serviceVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        [serviceVC customNavigationTitle:@"咨询管理"];
        serviceVC.selectedTab = 0;
        serviceVC.forSaleService = YES;
        [self.navigationController pushViewController:serviceVC animated:YES];
    } else if (tag == 4) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"待审核",@"同意",@"不同意"];
        NSArray *stateArray = @[@"1",@"2",@"3"];
        
        for (int i = 0; i < 3; i ++) {
            STMStoreRefundViewController *childVC = [[STMStoreRefundViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.lock = @"2";
            childVC.state = stateArray[i];
            [vcArray addObject:childVC];
        }
        NSMutableArray *vcArrayTwo = [NSMutableArray array];
        for (int i = 0; i < 3; i ++) {
            STMStoreRefundViewController *childVC = [[STMStoreRefundViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.lock = @"1";
            childVC.state = stateArray[i];
            [vcArrayTwo addObject:childVC];
        }
        STMTrueOrderViewController *firstVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        STMTrueOrderViewController *secondVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArrayTwo];
        firstVC.selectedTab = 0;
        secondVC.selectedTab = 0;
        firstVC.forOrderManagement = YES;
        secondVC.forOrderManagement = YES;
        firstVC.title = @"售前退款";
        secondVC.title = @"售后退款";
        STMOrderManagementMainController *vc = [[STMOrderManagementMainController alloc] init];
        vc.viewControllers = @[firstVC, secondVC];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (tag == 5) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"待审核",@"同意",@"不同意"];
        NSArray *stateArray = @[@"1",@"2",@"3"];

        for (int i = 0; i < 3; i ++) {
            STMStoreRefundViewController *childVC = [[STMStoreRefundViewController alloc] init];
            childVC.forGoodsReturn = YES;
            childVC.title = titleArray[i];
            childVC.lock = @"2";
            childVC.state = stateArray[i];
            [vcArray addObject:childVC];
        }
        NSMutableArray *vcArrayTwo = [NSMutableArray array];
        for (int i = 0; i < 3; i ++) {
            STMStoreRefundViewController *childVC = [[STMStoreRefundViewController alloc] init];
            childVC.forGoodsReturn = YES;
            childVC.title = titleArray[i];
            childVC.lock = @"1";
            childVC.state = stateArray[i];
            [vcArrayTwo addObject:childVC];
        }
        STMTrueOrderViewController *firstVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        STMTrueOrderViewController *secondVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArrayTwo];
        firstVC.selectedTab = 0;
        secondVC.selectedTab = 0;
        firstVC.forOrderManagement = YES;
        secondVC.forOrderManagement = YES;
        firstVC.title = @"售前退货";
        secondVC.title = @"售后退货";
        STMOrderManagementMainController *vc = [[STMOrderManagementMainController alloc] init];
        vc.viewControllers = @[firstVC, secondVC];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (tag == 6) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"7天",@"30天"];
        NSArray *indexArray = @[@"8",@"9"];
        
        for (int i = 0; i < 2; i ++) {
            STMTopTenFlowViewController *childVC = [[STMTopTenFlowViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.VCindex = indexArray[i];
            [vcArray addObject:childVC];
        }
        STMTrueOrderViewController *serviceVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        [serviceVC customNavigationTitle:@"店铺流量"];
        serviceVC.selectedTab = 0;
        serviceVC.forSaleService = YES;
        [self.navigationController pushViewController:serviceVC animated:YES];
    } else if (tag == 7) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"7天",@"30天"];
        NSArray *indexArray = @[@"4",@"5"];
        NSArray *indexArrayTwo = @[@"6",@"7"];
        for (int i = 0; i < 2; i ++) {
            STMTopTenFlowViewController *childVC = [[STMTopTenFlowViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.VCindex = indexArray[i];
            [vcArray addObject:childVC];
        }
        NSMutableArray *vcArrayTwo = [NSMutableArray array];
        for (int i = 0; i < 2; i ++) {
            STMTopTenFlowViewController *childVC = [[STMTopTenFlowViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.VCindex = indexArrayTwo[i];
            [vcArrayTwo addObject:childVC];
        }
        STMTrueOrderViewController *firstVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        STMTrueOrderViewController *secondVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArrayTwo];
        firstVC.selectedTab = 0;
        secondVC.selectedTab = 0;
        firstVC.forOrderManagement = YES;
        secondVC.forOrderManagement = YES;
        firstVC.title = @"下单金额";
        secondVC.title = @"下单量";
        STMOrderManagementMainController *vc = [[STMOrderManagementMainController alloc] init];
        vc.viewControllers = @[firstVC, secondVC];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (tag == 8) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"商品流量",@"商品下单金额",@"商品下单量"];
        NSArray *indexArray = @[@"1",@"2",@"3"];
        for (int i = 0; i < 3; i ++) {
            STMTopTenFlowViewController *childVC = [[STMTopTenFlowViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.VCindex = indexArray[i];
            [vcArray addObject:childVC];
        }
        STMTrueOrderViewController *serviceVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        [serviceVC customNavigationTitle:@"TOP10"];
        serviceVC.selectedTab = 0;
        serviceVC.forSaleService = YES;
        [self.navigationController pushViewController:serviceVC animated:YES];
    }  else if (tag == 9) {
        NSMutableArray *vcArray = [NSMutableArray array];
        NSArray *titleArray = @[@"出售中",@"仓库中",@"禁售商品"];
        NSArray *goodsTypeArray = @[@"",@"offline",@"lockup"];
        
        for (int i = 0; i < 3; i ++) {
            STMGoodsManagementViewController *childVC = [[STMGoodsManagementViewController alloc] init];
            childVC.title = titleArray[i];
            childVC.goodsType = goodsTypeArray[i];
            [vcArray addObject:childVC];
        }
        STMTrueOrderViewController *serviceVC = [[STMTrueOrderViewController alloc] initWithControllers:vcArray];
        [serviceVC customNavigationTitle:@"商品管理"];
        UIButton *publishButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
        [publishButton setTitle:@"发布商品" forState:UIControlStateNormal];
        publishButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [publishButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [publishButton addTarget:self action:@selector(publishButtonClick) forControlEvents:UIControlEventTouchUpInside];
        serviceVC.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:publishButton];
        
        serviceVC.selectedTab = 0;
        serviceVC.forSaleService = YES;
        [self.navigationController pushViewController:serviceVC animated:YES];
    } else if (tag == 10) {
        STMShopManagementViewController *vc = [[STMShopManagementViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (tag == 11) {
        STMServiceIMViewController *vc = [[STMServiceIMViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)iconTap {
    STMShopManagementViewController *vc = [[STMShopManagementViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)publishButtonClick {
    STMGoodsPublishViewController *publishVC = [[STMGoodsPublishViewController alloc] init];
    [publishVC customNavigationTitle:@"发布商品"];
    [self.navigationController pushViewController:publishVC animated:YES];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
